<template>
  <el-dialog
    v-model="dialogVisible"
    :title="t('logisticsClassification.selectCountry')"
    width="60%"
    :before-close="handleClose"
  >
    <div class="search-box">
      <el-input
        v-model="searchText"
        :placeholder="t('common.inputText')"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>
    <el-table
      ref="tableRef"
      :data="filteredData"
      style="width: 100%"
      height="400px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" :label="t('logisticsClassification.countryName')" />
      <el-table-column prop="code" :label="t('logisticsClassification.countryCode')" />
    </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">{{ t('common.cancel') }}</el-button>
        <el-button type="primary" @click="handleConfirm">
          {{ t('common.ok') }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { ElTable } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getCountryEnumApi } from '@/api/order'

const { t } = useI18n()

interface CountryItem {
  id: number
  name: string
  code: string
}

const dialogVisible = ref(false)
const tableRef = ref<InstanceType<typeof ElTable>>()
const tableData = ref<CountryItem[]>([])
const selectedCountries = ref<CountryItem[]>([])
const searchText = ref('')

const emit = defineEmits(['confirm'])

// 计算属性：根据搜索文本过滤数据
const filteredData = computed(() => {
  if (!searchText.value) return tableData.value
  const search = searchText.value.toLowerCase()
  return tableData.value.filter((item) => {
    const name = item.name || ''
    const code = item.code || ''
    return name.toLowerCase().includes(search) || code.toLowerCase().includes(search)
  })
})

const handleClose = () => {
  dialogVisible.value = false
  tableData.value = []
  selectedCountries.value = []
  searchText.value = ''
}

const handleSelectionChange = (selection: CountryItem[]) => {
  selectedCountries.value = selection
}

const handleConfirm = () => {
  emit('confirm', selectedCountries.value)
  handleClose()
}

const handleSearch = () => {
  // 搜索时自动滚动到顶部
  nextTick(() => {
    const tableBody = document.querySelector('.el-table__body-wrapper')
    if (tableBody) {
      tableBody.scrollTop = 0
    }
  })
}

const open = async (selectedData: CountryItem[], is_classification: boolean, id: string = '') => {
  dialogVisible.value = true
  try {
    interface ApiParams {
      is_classification: boolean
      id?: string
    }
    const params: ApiParams = { is_classification }
    if (id) {
      params.id = id
    }
    const res = await getCountryEnumApi(params)
    if (res.code === 0) {
      tableData.value = res.data
        .map((item: any) => ({
          id: item.id || 0,
          name: item.name || '',
          code: item.country_code || ''
        }))
        .filter((item) => item.name && item.code) // Filter out items with empty name or code
      // 设置已选中的数据
      nextTick(() => {
        selectedCountries.value = selectedData
        selectedData.forEach((item) => {
          const row = tableData.value.find((row) => row.id === item.id)
          if (row) {
            tableRef.value?.toggleRowSelection(row, true)
          }
        })
      })
    } else {
      ElMessage.error(t('common.requestFailed'))
    }
  } catch (error) {
    ElMessage.error(t('common.requestFailed'))
    console.error('Failed to fetch country data:', error)
  }
}

defineExpose({
  open
})
</script>

<style lang="less" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.search-box {
  margin-bottom: 16px;
}

:deep(.el-table) {
  .el-table__body-wrapper {
    overflow-y: auto;
  }
}
</style>
